<template>
	<div>
		<van-nav-bar title="标题" left-text="返回" left-arrow @click-left="onClickLeft" />
		<div v-if="item">
			<dl>
				<dt>
					<img :src="item.img" style="width: 100%;" />
				</dt>
				<dd>
					<p>{{ item.title }}</p>
					<p>{{ item.desc }}</p>
				</dd>
			</dl>
			<h2>评论列表</h2>
			<van-cell
				v-for="(v, i) in item.messageList"
				:key="i"
				:title="v.name + ' ' + v.datetime"
				size="large"
				:label="v.content"
				:icon="v.url"
			/>

			<van-cell-group inset>
				<van-field
					v-model="message.content"
					rows="2"
					autosize
					label="留言"
					type="textarea"
					maxlength="50"
					placeholder="请输入留言"
					show-word-limit
				/>
			</van-cell-group>

			<van-button block type="primary" @click="handleAddMess">添加评论</van-button>
		</div>

	</div>
</template>


<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { postsListDetail, postAddMess } from '@/api'
import { useRoute, useRouter } from 'vue-router'
import { Notify } from 'vant'
import { ListItemType } from '@/interface'
import { useStore } from 'vuex'
import { State } from '@/store'
/***************************详情信息******************************/

const route = useRoute()
const router = useRouter()
const id = route.params.id
const item = ref<ListItemType>()
const store = useStore<State>()
const getData = async () => {
	const resp = await postsListDetail({ id: id as string })
	const { code, data, mess } = resp.data

	if (code === 200) {
		item.value = data
		store.commit('addUserHistory', data)
	} else {
		Notify({
			type: 'danger',
			message: mess,
			onClose() {
				router.push('/')
			}
		})
	}
}

const onClickLeft = () => history.back();
onMounted(() => {
	getData()
})

/***************************评论******************************/

const isLogin = computed(() => store.state.user.isLogin)
const username = computed(() => store.state.user.username)
const message = reactive({
	name: '',
	content: '',
	datetime: '',
	url: require('../../assets/logo.png')
})
const handleAddMess = async () => {
	// 验证登录
	if (!isLogin.value) {
		router.push({ name: 'login' })
		return
	}

	// 添加评论
	if (message.content === "") {
		Notify({ type: 'danger', message: '评论内容不可以为空' })
	} else {
		message.datetime = new Date().toLocaleString()
		message.name = username.value

		const resp = await postAddMess({ id: id as string, data: message })
		const { code, data, mess } = resp.data
		
		if(code === 200) {
			Notify({ type: 'success', message: mess })
			getData()
		} else {
			Notify({ type: 'danger', message: mess })
		}
	}

}
</script>


<!-- <style>

</style> -->